<?php
/**
 * Created by PhpStorm.
 * User: gakuin
 * Date: 7/7/16
 * Time: 1:19 PM
 */
namespace app\models;

use Yii;
use yii\base\Model;
use yii\captcha\Captcha;

class SignupForm extends Model
{
    public $username;
    public $password;
    public $password2;
    public $mobile;
    public $code;
    public $verifyCode;

    public function rules()
    {
        return [
            ['username', 'required','message'=>'用户名不能为空'],
            ['password', 'required','message'=>'密码不能为空'],
            ['password','string','min'=>'6','max'=>'12','tooShort'=>'密码至少为6位英文或数字','tooLong'=>'密码最多为12位英文或数字'],
            ['password2','compare','compareAttribute'=>'password','message'=>'两次密码必须一致'],
            ['username', 'string','max'=>'12','tooLong'=>'用户名最多为12位中文英文或数字'],
            ['username', 'unique', 'targetClass' => 'app\models\User', 'message' => '用户名已存在'],
            ['mobile','uniqueTel'],
            ['mobile', 'required','message'=>'手机号不能为空'],
            ['code', 'required','message'=>'验证码不能为空'],
            //验证输入的和表中保存的验证码
            ['code','validateCode'],
            //['verifyCode', 'captcha'],
        ];
    }
    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
            'password2'=>'确认密码',
            'mobile' =>'手机号',
            'code' =>'验证码',
            'verifyCode' => '图形验证',
        ];
    }
    public function validateCode($attribute,$params){

        $tel = $this->mobile;
        $now = time()+3600*6;
        $verify = ValidateCode::find()->where(['mobile'=>$tel])->orderBy('create_time DESC')->one();

        if($verify == null){
            $this->addError($attribute,'请发送验证码');
        }else{
            $create = strtotime($verify->create_time);
            if ($create<$now-60) {

                $this->addError($attribute, '验证码过期,请重新发送验证码');
                //return;
            }elseif($verify->verify_code!=$this->code){
                $this->addError($attribute, '验证码不正确');
            }
        }

    }
    public function uniqueTel($attribute,$params){
        $tel = $this->mobile;
        $user = User::find()->where(['mobile'=>$tel])->one();
        if($user!=null){
            $this->addError($attribute,'手机号已被注册');
        }
    }


}